package com.iot08.push.mqtt.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iot08.common.utils.StringUtil;
import com.iot08.push.mqtt.conf.MqttConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @version 1.0
 * @Description: mqtt消费服务逻辑处理
 * @time: 2020/9/25 11:03
 * @author: Rock
 */
@Slf4j
@Component
public class MqttReceive {

    //@Resource
    //private RedisService redisService;

    /**
     * @time: 2020/9/25 11:05
     * @author: Rock
     * @version 1.0
     */
    @Bean
    @ServiceActivator(inputChannel = MqttConfig.CHANNEL_NAME_IN)
    public MessageHandler inboundHandler() {
        return new MessageHandler() {
            public void handleMessage(Message<?> message) throws MessagingException {
                //log.info("----MQTT message = {}", message);
                Map<String, Object> headers = message.getHeaders();
                Object topic = headers.get("mqtt_receivedTopic");
                //逻辑处理
                if (message.getPayload() != null) {
                    JSONObject jsonData = JSON.parseObject(message.getPayload().toString());
                    /*if(jsonData != null && StringUtil.isNotBlank(jsonData.getString("user_id"))){
                        //删除缓存操作
                        String userId = jsonData.getString("user_id");
                        if(StringUtil.isNotBlank(jsonData.get("focus"))){
                            redisService.hset("User:" + userId, "app_focus", "1");
                        } else {
                            redisService.hdel("User:" + userId, "app_focus");
                        }
                    }*/
                    if (jsonData != null) {
                        String type = jsonData.getString("type");
                        String uuid = jsonData.getString("UUID");
                        if (StringUtil.isNotBlank(uuid)) {
                            if ("online".equals(type)) {
                                //在线
                                //redisService.setex("MQ:" + uuid, 60*60*24*7, message.getPayload().toString());
                            } else {
                                //不在线
                                //redisService.del("MQ:" + uuid);
                            }
                        } else {
                            log.info("UUID is null : {}", jsonData);
                        }
                    } else {
                        log.info("jsonData is null");
                    }
                } else {
                    log.info("message.getPayload() is null");
                }
            }
        };
    }
}
